//USART
//LOW
//Crystal= 4 MHz; Baud Rate = 1.2k; SPBRG = 51,
//Crystal= 4 MHz; Baud Rate = 2.4k; SPBRG = 25,
//Crystal= 4 MHz; Baud Rate = 9.6k; SPBRG = 6, not work
//Crystal= 4 MHz; Baud Rate = 19.2k; SPBRG = 2, not work
//HIGH
//Crystal= 4 MHz; Baud Rate = 1.2k; SPBRG = 207,
//Crystal= 4 MHz; Baud Rate = 2.4k; SPBRG = 103,
//Crystal= 4 MHz; Baud Rate = 9.6k; SPBRG = 25,
//Crystal= 4 MHz; Baud Rate = 19.2k; SPBRG = 12, 
//Crystal= 4 MHz; Baud Rate = 57.6k; SPBRG = 3, not work
//Crystal= 4 MHz; Baud Rate = 115.2k; SPBRG = 1, not work

//LOW
//Crystal= 20 MHz; Baud Rate = 1.2k; SPBRG = 255, not work
//Crystal= 20 MHz; Baud Rate = 2.4k; SPBRG = 129, not work
//Crystal= 20 MHz; Baud Rate = 9.6k; SPBRG = 31, work
//Crystal= 20 MHz; Baud Rate = 19.2k; SPBRG = 15, 
//Crystal= 20 MHz; Baud Rate = 57.6k; SPBRG = 4, 
//Crystal= 20 MHz; Baud Rate = 115.2k; SPBRG = 2, work

//HIGH
//Crystal= 20 MHz; Baud Rate = 9.6k;; SPBRG = 129,
//Crystal= 20 MHz; Baud Rate = 19.2k; SPBRG = 64,
//Crystal= 20 MHz; Baud Rate = 57.6k; SPBRG = 21,
//Crystal= 20 MHz; Baud Rate = 115.2k; SPBRG = 10,

#include<p18F4520.h>
#include <usart.h>
#include <delays.h>

#pragma config OSC = HS
#pragma config WDT = OFF // turns the watchdog timer off

char Data[3]; 
unsigned char c;

void main()
{
  PORTA = 0x00;
  TRISA = 0b00000000;

  TRISC = 0x00;	
  OpenUSART(USART_TX_INT_OFF & 
			USART_RX_INT_OFF & 
			USART_ASYNCH_MODE & 
			USART_EIGHT_BIT &   
			USART_CONT_RX & 
			USART_BRGH_HIGH, 10);
			
//BAUD RATE FORMULAS:	
//SYNC = 0, BRGH = 0, BRG16 = 0
//baud rate= FOSC / (64 * (spbrg + 1)) 
//baud rate=   20M / (64 * (255 + 1)) 	= 1200

//BAUD RATE = 1200; spbrg = 51
//BAUD RATE = 9600; spbrg = 6

/*Function Description
BusyUSART Is the USART transmitting?
CloseUSART Disable the USART.
DataRdyUSART Is data available in the USART read buffer?
getcUSART Read a byte from the USART.
getsUSART Read a string from the USART.
OpenUSART Configure the USART.
putcUSART Write a byte to the USART.
putsUSART Write a string from data memory to the USART.
putrsUSART Write a string from program memory to the USART.
ReadUSART Read a byte from the USART.
WriteUSART Write a byte to the USART. */
			 
  while(1)
  { 
    //main loop
    //wait for byte from USART,
    //and report result back
/* no works- buffer problem
    while(!DataRdyUSART());
    getsUSART(Data,3);
    putsUSART(Data);
*/    
 
// the code below works for read char 
	while(!DataRdyUSART());

    c = getcUSART(); //c = ReadUSART();
    PORTAbits.RA2 = 1;
	Delay10KTCYx(100);
    WriteUSART ( c );

    PORTAbits.RA2 = 0;
	Delay10KTCYx(100);

	if (c=='1')
	{
	  PORTAbits.RA0 = 1;
      putrsUSART("On1");
      Delay10KTCYx(100);
    }
    if (c=='2')
    {
	  PORTAbits.RA0 = 0;
      putrsUSART("Off2");
      Delay10KTCYx(100);
    }

      //CloseUSART(); 
  }
}
